package models

import "go-project/common"

type ArticleComment struct {
	ID            uint   `gorm:"primary_key" json:"id"`
	Content       string `gorm:"type:text;not null;comment:'文章评论内容'"`
	ArticleId     uint   `gorm:"not null;comment:'文章id'"`
	Uid           uint   `gorm:"not null;comment:'评论用户id'"`
	UpvoteCount   int    `json:"upvote_count"`
	DownvoteCount int    `json:"downvote_count"`
	ReplyId       uint   `json:"reply_id"`
	AuthorType    int8   `json:"author_type"`
	ReplyToUserId uint   `json:"reply_to_user_id"`
	IsBanned      int8   `json:"is_banned"`
	Model
}

func (comment *ArticleComment) TableName() string {
	return "article_comments"
}

func (comment *ArticleComment) BannedChildComment(commentID uint) error {
	var articleComments []ArticleComment
	result := common.DB.Table(comment.TableName()).Where("reply_id=?", commentID).Find(&articleComments)
	if err := result.Error; err != nil {
		return err
	}
	for _, articleComment := range articleComments {
		articleComment.IsBanned = 1
		updateResult := common.DB.Save(&articleComment)
		if err := updateResult.Error; err != nil {
			return err
		}
		err := comment.BannedChildComment(articleComment.ID)
		if err != nil {
			return err
		}
	}
	return nil

}

func (comment *ArticleComment) DelChildComment(commentID uint) error {
	var articleComments []ArticleComment
	result := common.DB.Table(comment.TableName()).Where("reply_id=?", commentID).Find(&articleComments)
	if err := result.Error; err != nil {
		return err
	}
	for _, articleComment := range articleComments {
		delResult := common.DB.Delete(&articleComment)
		if err := delResult.Error; err != nil {
			return err
		}
		err := comment.DelChildComment(articleComment.ID)
		if err != nil {
			return err
		}
	}
	return nil
}
